
from flask import Flask, render_template, jsonify, request
from flask_cors import CORS
import json

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f"Point(x={self.x}, y={self.y})"
    
    def to_dict(self):
        return {"x": self.x, "y": self.y}

app = Flask(__name__)
CORS(app)

# 存储所有点的列表
points = []

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/points', methods=['GET'])
def get_points():
    """获取所有坐标点"""
    return jsonify([point.to_dict() for point in points])

@app.route('/api/points', methods=['POST'])
def add_point():
    """添加新坐标点"""
    data = request.json
    x = data.get('x')
    y = data.get('y')
    
    if x is not None and y is not None:
        point = Point(float(x), float(y))
        points.append(point)
        return jsonify({"success": True, "point": point.to_dict()})
    return jsonify({"success": False, "error": "Invalid coordinates"}), 400

@app.route('/api/points/<int:index>', methods=['DELETE'])
def delete_point(index):
    """删除指定索引的坐标点"""
    if 0 <= index < len(points):
        deleted_point = points.pop(index)
        return jsonify({"success": True, "point": deleted_point.to_dict()})
    return jsonify({"success": False, "error": "Point not found"}), 404

@app.route('/api/points/<int:index>', methods=['PUT'])
def update_point(index):
    """更新指定索引的坐标点"""
    if 0 <= index < len(points):
        data = request.json
        x = data.get('x')
        y = data.get('y')
        
        if x is not None and y is not None:
            points[index].x = float(x)
            points[index].y = float(y)
            return jsonify({"success": True, "point": points[index].to_dict()})
    return jsonify({"success": False, "error": "Point not found or invalid coordinates"}), 404

@app.route('/api/points/clear', methods=['POST'])
def clear_points():
    """清空所有坐标点"""
    points.clear()
    return jsonify({"success": True})

@app.route('/api/points/export', methods=['GET'])
def export_points():
    """导出坐标点为JSON"""
    return jsonify({
        "points": [point.to_dict() for point in points],
        "count": len(points)
    })

if __name__ == '__main__':
    app.run(debug=True, port=5000)
